package com.miplus.ccrm.core.service.action;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.base.MPJBaseServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.miplus.ccrm.common.CmdResVo;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.ServiceException;
import com.miplus.ccrm.core.controller.vo.action.*;
import com.miplus.ccrm.core.controller.vo.conf.WfNextStepVo;
import com.miplus.ccrm.core.pojo.FiCreditcases;
import com.miplus.ccrm.core.pojo.FiDelay;
import com.miplus.ccrm.core.pojo.FiRelief;
import com.miplus.ccrm.core.pojo.FiReturn;
import com.miplus.ccrm.core.mapper.FiReturnMapper;
import com.miplus.ccrm.core.service.FiWorkFlowCase;
import com.miplus.ccrm.core.service.collect.FiTaskService;
import com.miplus.ccrm.core.service.collect.FiCreditcasesService;
import com.miplus.ccrm.core.service.strategy.CpCalllistService;
import com.miplus.ccrm.core.utils.EnumConfirmStatus;
import com.miplus.ccrm.core.utils.EnumFiChannel;
import com.miplus.ccrm.core.utils.EnumWorkFlowStep;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
* @author pc
* @description 针对表【fi_return(案件退回申请表)】的数据库操作Service实现
* @createDate 2024-04-08 10:12:37
*/
@Slf4j
@Service
public class FiReturnServiceImpl extends MPJBaseServiceImpl<FiReturnMapper, FiReturn>
    implements FiReturnService{

    @Resource
    private FiTaskService fiTaskService;
    @Resource
    private CpCalllistService cpCalllistService;
    @Resource
    private FiWorkFlowCase fiWorkFlowCase;
    @Resource
    private FiCreditcasesService fiCreditcasesService;

    @Override
    public IPage<FiReturnResVo> fiReturnList(String $usrid, FiApplyReqVo paras)

    {
        return selectJoinListPage(new Page<>(paras.getPageNum(), paras.getPageSize()),
                FiReturnResVo.class,
                new MPJLambdaWrapper<FiReturn>()
                        .selectAs("fun_getnames('FI.RETURN.STATUS',t.status)", FiReturnResVo::getStatusdsc)
                        .selectAs("fun_getnames('FI.RETURN.REASON',t.applyreason)", FiReturnResVo::getApplyreasondsc)
                        .selectAs("(select cl.wfid from cp_calllist cl where cl.clid=t.clid)", FiReturnResVo::getWfid)
                        .selectAs("fun_getgrpname(t.applyusr)",FiReturnResVo::getApplygrpname)
                        .selectAll(FiReturn.class)
                        .apply("fc_hasApplyView(t.applynumber,'SYS_RETURN',t.applyusr,{0},t.status,t.confirmusr)>0",$usrid)
                        .apply(JPubUtils.IsNotEmpty(paras.getApplygrp()),"fc_hasUsrInGroup(t.applyusr,{0})>0",paras.getApplygrp())
                        .eq(JPubUtils.IsNotEmpty(paras.getFicaseid()), FiReturn::getFicaseid,paras.getFicaseid())
                        .eq(JPubUtils.IsNotEmpty(paras.getStatus()),FiReturn::getStatus,paras.getStatus())
                        .eq(JPubUtils.IsNotEmpty(paras.getApplyusr()),FiReturn::getApplyusr,paras.getApplyusr())
                        .between(JPubUtils.IsNotEmpty(paras.getStartdt()), FiReturn::getApplydt,JPubUtils.StringToDate(paras.getStartdt()),JPubUtils.StringToDate(paras.getEnddt()))
                        .orderByAsc(FiReturn::getApplydt)
        );
    }

    @Override
    @Transactional
    public CmdResVo fiReturnAdd(String $usrid, FiReturnAddVo paras)
    {
        //1=待审核
        FiReturn fiReturn=selectJoinOne(FiReturn.class,
                new MPJLambdaWrapper<FiReturn>()
                        .eq(FiDelay::getFicaseid,paras.getFicaseid())
                        .eq(FiDelay::getStatus, EnumConfirmStatus.Pending.value)
        );
        //相同的案件正在审核中
        if(fiReturn!=null){
            throw new ServiceException(EnumRCode.DataPending.value, EnumRCode.DataPending.name);
        }
        String clid=paras.getClid();
        if(JPubUtils.IsNotEmpty(clid)){
            clid="SYS_RETURN"; //此任务是系统配置任务，不能delete
        }

        Integer wfid=cpCalllistService.getCalllistWfID(clid);

        //CAMPAIGN.CHANNEL=11留案
        int tasknumber=fiTaskService.addTask($usrid,clid,paras.getFicaseid(), EnumFiChannel.Return.value);

        int ret=0;
        log.info("applyAdd:clid={},ficase={},tasknumber={},wfid={}",clid,paras.getFicaseid(),tasknumber,wfid);

        FiReturn fi = new FiReturn();
        fi.setClid(clid);
        fi.setApplyreason(paras.getApplyreason());
        fi.setFicaseid(paras.getFicaseid());
        fi.setApplydsc(paras.getApplydsc());
        fi.setTasknumber(tasknumber);
        fi.setStatus(EnumConfirmStatus.New.value); //新建
        fi.setApplydt(new Date());
        fi.setApplyusr($usrid);
        ret=baseMapper.insert(fi);

        int applynumber=fi.getApplynumber();

        if(wfid>0){
            //wfid=0 表示此任务clid没有配置工作流，前台可以根据是否有wfid显示不通的审批流程或状态
            String status=fiWorkFlowCase.doCreate($usrid,wfid,applynumber,tasknumber);
            fi = new FiReturn();
            fi.setApplynumber(applynumber);
            fi.setStatus(Integer.parseInt(status)); //处理中
            baseMapper.updateById(fi);
        }

        return new CmdResVo(ret,Integer.toString(applynumber));
    }

    @Override
    public CmdResVo fiReturnCancel(String $usrid, FiApplyCancelVo paras)
    {
        FiReturn fi=baseMapper.selectById(paras.getApplynumber());
        if(JPubUtils.IsNotEmpty(fi.getTasknumber())){
            fiTaskService.updateStatus(fi.getTasknumber(),$usrid,"X");
        }
        else{
            log.warn("applyCancel:getTasknumber.isnull");
        }
        Integer wfid=cpCalllistService.getCalllistWfID(fi.getClid());
        fiWorkFlowCase.doCancel($usrid,wfid,fi.getApplynumber());

        fi = new FiReturn();
        fi.setApplynumber(paras.getApplynumber());
        fi.setStatus(EnumConfirmStatus.Cancel.value); //取消
        fi.setCancelusr($usrid);
        fi.setCanceldt(new Date());
        int ret=baseMapper.updateById(fi);

        return new CmdResVo(ret,fi.getApplynumber().toString());
    }

    @Override
    public CmdResVo fiReturnConfirm(String $usrid, FiApplyConfirmVo paras)
    {
        boolean confirmend=true;
        FiReturn fiReturn=baseMapper.selectById(paras.getApplynumber());
        String okstatus=paras.getActionid().toString();
        if(JPubUtils.IsNotEmpty(paras.getCaseactid())){
            //需要走工作流
            WfNextStepVo wfNextStepVo=fiWorkFlowCase.doExec($usrid,paras.getCaseactid(),
                    paras.getActionid(),paras.getWfcaseid(),paras.getConfirmdsc()
            );
            okstatus=wfNextStepVo.getStatus();

            //可能有多级审核,3=审核全部完成
            if(!JPubUtils.IsEqual(wfNextStepVo.getType(), EnumWorkFlowStep.End.value)) {
                confirmend=false;
            }
        }
        else{
            Integer wfid=cpCalllistService.getCalllistWfID(fiReturn.getClid());
            if(wfid==null||wfid==0){//不使用工作流,这种情况下okstatus就是字典ID，直接写审核结果
                log.info("fiReturnConfirm.nouse workflow：okstatus={}",okstatus);
            }
            else{//可能配置错误或网络引起的，2024-08-29
                log.warn("fiReturnConfirm.nofind wf caseactid.");
                throw new ServiceException(EnumRCode.WfDataErr.value, EnumRCode.WfDataErr.name);
            }
        }

        //单纯就是审批流程，结果客户在这里写，如果有后续反馈的，在result里面写，比如外访
        if(JPubUtils.IsNotEmpty(fiReturn.getTasknumber())&&confirmend) {
            if(JPubUtils.IsEqual(okstatus,EnumConfirmStatus.Pass.value)){//审核通过
                FiCreditcases fcase=fiCreditcasesService.getById(fiReturn.getFicaseid());
                log.info("applyConfirm.Ok:ficaseid={} return", fiReturn.getFicaseid());
                fcase.setStatus(4); //退回
                fcase.setCcc("O");
                fcase.setSendtousr(null);
                fcase.setSendtodept(null);
                fcase.setStatusdt(new Date());
                fcase.setMdusr($usrid);
                fcase.setMddt(new Date());
                fiCreditcasesService.getBaseMapper().updateById(fcase);
            }
            fiTaskService.updateStatus(
                    fiReturn.getTasknumber(),
                    $usrid,
                    fiWorkFlowCase.getPassStatus(okstatus)
            );
        }

        FiReturn fi = new FiReturn();
        fi.setApplynumber(paras.getApplynumber());
        fi.setStatus(Integer.parseInt(okstatus));
        fi.setConfirmusr($usrid);
        fi.setConfirmdt(new Date());
        fi.setConfirmdsc(paras.getConfirmdsc());
        int ret=baseMapper.updateById(fi);

        return new CmdResVo(ret,paras.getApplynumber().toString());
    }
}




